package com.blue.wechat.invoke.spi.media;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blue.core.dict.HttpMethod;
import com.blue.wechat.cache.Wechat;
import com.blue.wechat.invoke.BaseInvoker;
import com.blue.wechat.invoke.InvokeException;
import com.blue.wechat.invoke.WechatInvoker;
import com.blue.wechat.invoke.annotation.WechatUrl;
import com.blue.wechat.invoke.model.media.UploadMedia;

/**
 * 新增图文素材的图片
 * 
 * @author zhengj
 * @since 1.0 2017年6月9日
 */
@WechatUrl(WechatInvoker.ADD_MEDIA_IMAGE)
public class AddMediaImageInvoker extends BaseInvoker<String>
{
	public AddMediaImageInvoker()
	{
	}

	@Override
	protected WechatInvoker getInvoker()
	{
		return WechatInvoker.ADD_MEDIA_IMAGE;
	}
	
	@Override
	protected String invoke(String url, HttpMethod method, Object post) throws Exception
	{
		if (!(post instanceof UploadMedia))
			throw new InvokeException("新增图文素材的图片参数类型不是 " + UploadMedia.class.getName());
		
		UploadMedia message = (UploadMedia)post;
		File file = message.getFile();
		Map<String, File> fileParam = new HashMap<>();
		fileParam.put("media", file);
		String resp = httpInvoker.upload(url, null, fileParam);
		return resp;
	}

	@Override
	protected String handleSuccess(String resp, Wechat wechat)
	{
		JSONObject object = JSON.parseObject(resp);
		String url = object.getString("url");
		return url;
	}
	
	
}
